<script setup lang="ts">
  import routerComponentName from '@/config/route-component-name/index'
  import DateRange from '@/components/business/date-range/DateRange.vue'
  import Pagination from '@/components/Pagination/index.vue'
  import ReceivePaymentFormModal from '@/components/pages/withdrawal/receive-payment/form-modal/index.vue'
  import { h, onMounted, ref } from 'vue'
  import {
    useGetReceivePaymentList,
    useGetReceivePaymentListQty,
    useWriteBackNoSyncReceivePayment,
  } from '@/services/pages/withdrawal/receive-payment/useReceivePayment'
  import { ElDivider, ElMessage, ElMessageBox, TableColumnCtx } from 'element-plus'
  import { receivePaymentExportExcel } from '@/api/withdrawal'
  import moment from 'moment'
  import MultipleCheckModal from '@/components/pages/withdrawal/receive-payment/check-modal/multiple.vue'
  import ReceivePaymentDetail from '@/components/pages/withdrawal/receive-payment/detail-modal/index.vue'
  import SingleCheckModal from '@/components/pages/withdrawal/receive-payment/check-modal/single.vue'
  import { useRouter } from 'vue-router'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { list, listTotal, getListParam, getListLoading, getList, resetFilter } =
    useGetReceivePaymentList()
  const { listQty, getListQtyLoading, getListQty } = useGetReceivePaymentListQty()
  const { writeBackLoading, write } = useWriteBackNoSyncReceivePayment()

  defineOptions({
    name: routerComponentName.financialSettlement.receivePaymentList,
  })

  interface SummaryMethodProps {
    columns: TableColumnCtx<WithdrawalReceivePayment>[]
    data: WithdrawalReceivePayment[]
  }

  // 全局路由对象
  const router = useRouter()

  // 正在预览详情的id
  const visiblingReceivePaymentId = ref('')

  // 收款单表单弹窗显示状态
  const receivePaymentFormModalVisible = ref(false)

  // 分页组件实例
  const paginationInsatnce = ref<InstanceType<typeof Pagination> | null>(null)

  // 日期范围选择组件实例
  const dateRangeInstance = ref<InstanceType<typeof DateRange> | null>(null)

  // 导出加载
  const exportLoading = ref(false)

  // 审核弹窗显示状态
  const checkModalVisible = ref(false)

  // 需要审核的id
  const needCheckId = ref('')

  // 详情弹窗显示状态
  const detailModalVisible = ref(false)

  // 单个审核弹窗显示状态
  const singleCheckModalVisible = ref(false)

  // 选择的收款单
  const selectedList = ref<Array<WithdrawalReceivePayment>>([])

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInsatnce.value) {
      getListParam.value.limit = paginationInsatnce.value.size
      getListParam.value.page = paginationInsatnce.value.current
      getList()
    }
  }

  /**
   * 日期范围更新事件
   * @param {object} param - 选择的日期
   * @param {string} param.startDate - 开始日期
   * @param {string} param.endDate - 结束日期
   */
  const handleDateRangeChange = (param: { startDate: string; endDate: string }) => {
    getListParam.value.startTime = param.startDate
    getListParam.value.endTime = param.endDate
    if (param.startDate && param.endDate) {
      _getList()
    }
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    resetFilter()
    if (dateRangeInstance.value) {
      dateRangeInstance.value.clearDate()
    }
    _getList()
  }

  /**
   * 导出事件
   */
  const onExport = () => {
    let isExportAllData = true
    getListParam.value.endTime && (isExportAllData = false)
    getListParam.value.startTime && (isExportAllData = false)
    getListParam.value.receivePaymenNo && (isExportAllData = false)
    getListParam.value.workNo && (isExportAllData = false)
    getListParam.value.status && (isExportAllData = false)

    ElMessageBox({
      type: 'warning',
      message: isExportAllData
        ? '当前筛选条件为空，将导出全部付款单，是否确定？'
        : '是否导出所筛选的付款单？',
      showCancelButton: true,
      confirmButtonText: isExportAllData ? '确定' : '是',
      cancelButtonText: isExportAllData ? '取消' : '否',
      title: '提示',
    })
      .then(() => {
        exportLoading.value = true
        receivePaymentExportExcel(getListParam.value).then((res) => {
          exportLoading.value = false
          ElMessage({
            type: res.data.code && !res.data.success ? 'error' : 'success',
            message:
              res.data.code && !res.data.success ? res.data.message : '付款单资料数据导出成功',
            plain: true,
            duration: 5000,
            showClose: true,
          })
          if (res.data.code && !res.data.success) {
            return
          }
          const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
          const link = document.createElement('a')
          link.href = url
          link.download = `付款单资料_${moment(new Date()).format('YYYYMMDD')}.xlsx`
          link.click()
        })
      })
      .catch(() => {
        // 不可以删除该注释，否则会引起报错
      })
  }

  /**
   * 收款表单弹窗更新事件
   */
  const onReceivePaymentFormModalUpdate = () => {
    _getList()
    getListQty()
  }

  /**
   * 状态点击事件
   */
  const onTabClick = () => {
    // if (getListParam.value.status === '') {
    //   getListParam.value.status = null
    // }
    _getList()
  }

  /**
   * 列表审核点击事件
   * @param {string} id - 付款单id
   */
  const handleCheckClick = (id: string) => {
    needCheckId.value = id
    singleCheckModalVisible.value = true
  }

  /**
   * 收款单号点击事件
   * @param {string} id - 收款单id
   */
  const handleReceivePaymentNoClick = (id: string) => {
    visiblingReceivePaymentId.value = id
    detailModalVisible.value = true
  }

  /**
   * 表格选择事件
   * @param {Array<WithdrawalReceivePayment>} _selectList - 选择的收款单
   */
  const handleSelectionChange = (_selectList: Array<WithdrawalReceivePayment>) => {
    selectedList.value = _selectList
  }

  /**
   * 批量审核点击事件
   */
  const onMultipleCheckClick = () => {
    checkModalVisible.value = true
  }

  /**
   * 表格多选的禁用状态控制方法
   * @param {WithdrawalReceivePayment} row - 付款单对象
   */
  const selectable = (row: WithdrawalReceivePayment) => {
    return row.status === 1
  }

  /**
   * 获取合计
   * @param param - 参数
   */
  const getSummaries = (param: SummaryMethodProps) => {
    const result: Array<string> = []
    param.columns.forEach((column, index) => {
      // 服务费合计
      if (index === 9) {
        result[9] = `￥${list.value
          .map((item) => Number(item.serviceTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 物料费合计
      if (index === 10) {
        result[10] = `￥${list.value
          .map((item) => Number(item.spareTotalFee))
          .reduce((prev, current) => prev + current, 0)
          .toFixed(2)}`
      }

      // 总费用
      if (index === 11) {
        let totalFee = 0
        list.value.forEach((item, index) => {
          totalFee += Number(calcRowTotalFee(index))
        })
        result[11] = `￥${totalFee.toFixed(2)}`
      }
    })
    return result
  }

  /**
   * 公司名称点击事件
   * @param {string} userId - 客户id
   */
  const handleUserNameClick = (userId: string) => {
    router.push({ path: `/user/userdetail/${userId}` })
  }

  /**
   * 同步点击事件
   * @param {string} id - 收款单id
   */
  const handleSyncClick = async (id: string) => {
    const res = await write(id)
    if (res.code === 20000) {
      HMessage.success('同步完成')
      return
    }
    HMessageBox.error(res.message)
  }

  /**
   * 计算某一行的总费用
   * @param {number} index - 行索引
   */
  const calcRowTotalFee = (index: number) => {
    const receiptPayment = list.value[index]
    const materialFee = receiptPayment.spareTotalFee || 0
    const serviceFee = receiptPayment.serviceTotalFee || 0
    const total = materialFee + serviceFee
    return Number((total || 0).toFixed(0)).toFixed(2)
  }

  /**
   * 工单单号点击事件
   * @param {string} orderId - 工单id
   */
  const handleOrderNoClick = (orderId: string) => {
    router.push(`/order/odetail/${orderId}`)
  }

  onMounted(() => {
    _getList()
    getListQty()
  })
</script>

<template>
  <div
    v-loading="getListLoading || exportLoading || getListQtyLoading"
    class="receive-payment-list"
  >
    <div class="container">
      <div class="btn-list">
        <el-tabs v-model="getListParam.status" @tab-change="onTabClick">
          <el-tab-pane :label="`全部（${listQty.total}）`" :name="''" />
          <el-tab-pane :label="`待审核（${listQty.waitCheckCount}）`" :name="1" />
          <el-tab-pane :label="`已审核（${listQty.CheckedCount}）`" :name="2" />
        </el-tabs>
      </div>
      <header class="header">
        <div class="btn-group">
          <h-plain-button
            v-permission="'receive_add'"
            @click="receivePaymentFormModalVisible = true"
            >新增收款单</h-plain-button
          >
          <h-plain-button
            v-permission="'receive_audit'"
            :disabled="selectedList.length <= 0"
            @click="onMultipleCheckClick"
            >批量审核</h-plain-button
          >
          <h-plain-button v-permission="'receive_export'" @click="onExport">导出</h-plain-button>
        </div>
        <div class="search">
          <date-range
            ref="dateRangeInstance"
            :start-date-width="140"
            :end-date-width="140"
            @change="handleDateRangeChange"
          />
          <el-input
            v-model="getListParam.receivePaymenNo"
            placeholder="请输入收款单号"
            clearable
            style="width: 140px"
            @clear="_getList"
          />
          <!-- <el-select v-model="getListParam.status" placeholder="状态">
            <el-option :value="1" label="待审核" />
            <el-option :value="2" label="已审核" />
          </el-select> -->
          <el-input
            v-model="getListParam.workNo"
            placeholder="请输入工单单号"
            clearable
            style="width: 140px"
            @clear="_getList"
          />
          <h-button type="primary" @click="_getList">
            <el-icon>
              <search></search>
            </el-icon>
            搜索
          </h-button>
          <h-button @click="onReset">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </h-button>
        </div>
      </header>
      <div class="main-footer">
        <div class="main">
          <el-table
            v-loading="writeBackLoading"
            :border="true"
            :data="list"
            height="100%"
            :summary-method="getSummaries"
            show-summary
            @selection-change="handleSelectionChange"
          >
            <!-- 选择 -->
            <el-table-column
              type="selection"
              fixed="left"
              :align="'center'"
              width="50"
              :selectable="selectable"
            />

            <!-- 序号 -->
            <el-table-column type="index" fixed="left" :align="'center'" width="50" label="序号" />

            <!-- 收款单号 -->
            <el-table-column
              width="128"
              prop="receivePaymentNo"
              show-overflow-tooltip
              label="收款单号"
            >
              <template #default="{ row }">
                <h-link @click="handleReceivePaymentNoClick(row.receivePaymentId)">{{
                  row.receivePaymentNo
                }}</h-link>
              </template>
            </el-table-column>

            <!-- 创建时间 -->
            <el-table-column width="128" prop="createTime" label="创建时间" />

            <!-- 状态 -->
            <el-table-column width="80" label="状态" :align="'center'">
              <template #default="{ row }">
                <div class="flex justify-center">
                  <h-status v-if="row.status === 1" type="warning">待审核</h-status>
                  <h-status v-else>已审核</h-status>
                </div>
              </template>
            </el-table-column>

            <!-- 关联工单 -->
            <el-table-column width="125" show-overflow-tooltip label="关联工单">
              <template #default="{ row }">
                <h-link
                  v-if="row.workMap.length == 1"
                  @click="handleOrderNoClick(row.workMap[0].workId)"
                  >{{ row.workMap[0].workNo }}</h-link
                >
                <template v-else>{{ `${row.workMap.length}张关联工单` }}</template>
              </template>
            </el-table-column>

            <!-- 送修公司 -->
            <el-table-column
              min-width="130"
              show-overflow-tooltip
              prop="repairCompanyUser"
              label="送修公司"
            >
              <template #default="{ row }">
                <h-link @click="handleUserNameClick(row.repairCompanyUserId)">{{
                  row.repairCompanyUser
                }}</h-link>
              </template>
            </el-table-column>

            <!-- 送修人 -->
            <el-table-column width="105" prop="sendForRepairUsername" label="送修人">
              <template #default="{ row }">
                <h-link @click="handleUserNameClick(row.sendForRepairUserId)">{{
                  row.sendForRepairUsername
                }}</h-link>
              </template>
            </el-table-column>

            <!-- 送修人手机 -->
            <el-table-column width="105" prop="sendForRepairPhone" label="送修人手机" />

            <!-- 服务费 -->
            <el-table-column width="100" label="服务费">
              <template #default="{ row }">
                ￥{{ (Number(row['serviceTotalFee']) || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 物料费 -->
            <el-table-column width="90" label="物料费">
              <template #default="{ row }">
                ￥{{ (Number(row['spareTotalFee']) || 0).toFixed(2) }}
              </template>
            </el-table-column>

            <!-- 总费用 -->
            <el-table-column width="110" label="总费用">
              <template #default="{ $index }"> ￥{{ calcRowTotalFee($index) }} </template>
            </el-table-column>

            <!-- 同步状态 -->
            <el-table-column width="90" label="反写状态">
              <template #default="{ row }">
                <h-status v-if="!row.yxkSyncState" type="warning">未反写</h-status>
                <template v-else>
                  <h-status v-if="!row.yxkSyncErrorMsg">反写成功</h-status>
                  <h-status v-else type="error">反写失败</h-status>
                </template>
              </template>
            </el-table-column>

            <!-- 反写失败原因 -->
            <el-table-column
              width="100"
              label="反写失败原因"
              show-overflow-tooltip
              prop="yxkSyncErrorMsg"
            >
              <template #default="{ row }">
                {{ row.yxkSyncState ? row.yxkSyncErrorMsg : '' }}
              </template>
            </el-table-column>

            <!-- 更新时间 -->
            <el-table-column width="128" prop="updateTime" label="更新时间" />

            <!-- 审核时间 -->
            <el-table-column width="128" prop="checkTime" label="审核时间" />

            <!-- 操作 -->
            <el-table-column width="100" label="操作" fixed="right" :align="'center'">
              <template #default="{ row }">
                <el-space :spacer="spacer" :size="0">
                  <h-link
                    v-if="row.status === 1"
                    v-permission="'receive_audit'"
                    @click="handleCheckClick(row.receivePaymentId)"
                    >审核</h-link
                  >
                  <h-link v-else v-permission="'receive_audit'" :disabled="true">审核</h-link>
                  <h-link v-if="row.status === 1 || !row.yxkSyncErrorMsg" :disabled="true"
                    >反写</h-link
                  >
                  <h-link v-else @click="handleSyncClick(row.receivePaymentId)">反写</h-link>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="footer">
          <Pagination
            ref="paginationInsatnce"
            :list_total="listTotal"
            @size-change="_getList"
            @current-change="_getList"
          />
        </div>
      </div>
    </div>

    <receive-payment-form-modal
      v-model="receivePaymentFormModalVisible"
      @update="onReceivePaymentFormModalUpdate"
    />

    <multiple-check-modal
      v-model="checkModalVisible"
      :id-list="selectedList.map((item) => item.receivePaymentId)"
      @update="_getList"
    />

    <receive-payment-detail
      v-model="detailModalVisible"
      :receive-payment-id="visiblingReceivePaymentId"
    />

    <single-check-modal
      v-model="singleCheckModalVisible"
      :receive-payment-id="needCheckId"
      @update="_getList"
    />
  </div>
</template>

<style scoped lang="scss">
  .receive-payment-list {
    padding: 12px;
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - 92px);

    .container {
      background-color: #fff;
      height: 100%;
      padding: 0 12px 12px 12px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;

      .header {
        display: flex;
        justify-content: space-between;

        .btn-group,
        .search {
          display: flex;
          column-gap: 5px;
        }
      }

      .main-footer {
        flex: 1;
        height: 0;
        display: flex;
        flex-direction: column;
        margin-top: 12px;
        row-gap: 12px;

        .main {
          max-height: calc(100% - 40px);
        }

        .footer {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }
</style>
